package org.ht.demo.openapi.util;

import java.util.zip.CRC32;

public class CRCUtils {

    //CRC校验段
    public static String getCRCString(String hexs) {
        //用于验证的数据
        byte[] b = getHexBytes(hexs);
        //得到校验后的字符串
        String value_string = getCRCValues(b);
        //补0 返回字符串
        return getRightLengths(value_string);
    }

    //扔进来校验
    public static String getCRCValues(byte[] b){
        CRC32 c = new CRC32();
        c.reset();//Resets CRC-32 to initial value.
        c.update(b, 0, b.length);//将数据丢入CRC32解码器
        int value = (int) c.getValue();//获取CRC32 的值  默认返回值类型为long 用于保证返回值是一个正数
        //转为16进制
        String value_string = Integer.toHexString(value);
        return value_string;
    }

    //将16进制的字符串转成字符数组
    public static byte[] getHexBytes(String str){
        byte[] bytes = new byte[str.length() / 2];
        for(int i = 0; i < str.length() / 2; i++) {
            String subStr = str.substring(i * 2, i * 2 + 2);
            bytes[i] = (byte) Integer.parseInt(subStr, 16);
        }
        return bytes;
    }

    //16进制补零
    public static String getRightLengths(String hexs){
        if (hexs.length() == 7){
            return 0+hexs;
        }else{
            return hexs;
        }
    }

}